<template>
  <div class="settings-container">
    <el-card class="settings-card">
      <template #header>
        <div class="card-header">
          <span>个人设置</span>
        </div>
      </template>
      <el-form :model="userProfile" label-width="100px" ref="profileForm">
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="uploadAvatar"
          >
            <img v-if="userProfile.avatarUrl" :src="userProfile.avatarUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><UserFilled /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="userProfile.username" disabled></el-input>
          <span style="color: red; margin-left: 10px;">Debug Username: {{ userProfile.username }}</span>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="userProfile.nickname"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveProfile">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { UserFilled } from '@element-plus/icons-vue'
import { userApi } from '@/api/user'
import { fileApi } from '@/api/file'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()
const userProfile = reactive({
  id: null,
  username: '',
  nickname: '',
  avatarUrl: ''
})

const profileForm = ref(null)

const fetchUserProfile = async () => {
  console.log('Attempting to fetch user profile...');
  try {
    console.log('Calling userApi.getCurrentUser()...');
    const response = await userApi.getCurrentUser()
    console.log('userApi.getCurrentUser() call returned. Response:', response);
    if (response.data.code === 200) {
      Object.assign(userProfile, response.data.data);
      console.log('userProfile after Object.assign:', userProfile);
    } else {
      ElMessage.error(response.data.message || '获取个人信息失败')
    }
  } catch (error) {
    console.error('Error during fetchUserProfile:', error);
    ElMessage.error('获取个人信息失败')
  }
}

const saveProfile = async () => {
  try {
    const response = await userApi.updateCurrentUser({
      nickname: userProfile.nickname,
      avatarUrl: userProfile.avatarUrl
    })
    if (response.data.code === 200) {
      ElMessage.success('个人信息更新成功')
      authStore.setUser(response.data.data)
    } else {
      ElMessage.error(response.data.message || '更新个人信息失败')
    }
  } catch (error) {
    console.error('更新个人信息失败:', error)
    ElMessage.error('更新个人信息失败')
  }
}

const resetForm = () => {
  fetchUserProfile()
}

const beforeAvatarUpload = (rawFile) => {
  const isJPGPNG = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png'
  const isLt2M = rawFile.size / 1024 / 1024 < 2

  if (!isJPGPNG) {
    ElMessage.error('头像图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

const uploadAvatar = async (options) => {
  try {
    const formData = new FormData()
    formData.append('file', options.file)
    const response = await fileApi.uploadFile(formData)
    if (response.data.code === 200) {
      userProfile.avatarUrl = response.data.data.fileUrl
      ElMessage.success('头像上传成功，请点击保存更新个人信息')
    } else {
      ElMessage.error(response.data.message || '头像上传失败')
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败')
  }
}

onMounted(() => {
  fetchUserProfile()
})
</script>

<style scoped>
.settings-container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  min-height: calc(100vh - var(--header-height)); /* 减去顶部导航栏高度 */
  padding: 40px 20px;
  background-color: var(--background-light);
}

.settings-card {
  width: 100%;
  max-width: 600px;
  border-radius: var(--border-radius-medium);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  color: var(--text-color-dark);
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--border-color);
  border-radius: var(--border-radius-medium);
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 120px;
  height: 120px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--primary-color);
}

.avatar-uploader-icon {
  font-size: 40px;
  color: var(--text-color-light);
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
}
</style> 